<template>
  <div class="amap-container">
    <!-- 地图容器 -->
    <div ref="mapContainer" class="map"></div>

    <!-- 地图控制面板 -->
    <div v-if="showControls" class="map-controls">
      <button
        @click="toggleAnimation"
        class="control-btn"
        :class="{ active: showAnimation }"
        :title="showAnimation ? '隐藏轨迹动画' : '显示轨迹动画'"
      >
        🎬
      </button>
      <button @click="startAnimation" class="anim-btn" title="开始动画">
        ▶️
      </button>
      <button @click="stopAnimation" class="anim-btn" title="停止动画">
        ⏹️
      </button>
      <button @click="resetAnimation" class="anim-btn" title="重置动画">
        🔄
      </button>
      <button @click="zoomIn" class="control-btn" title="放大">➕</button>
      <button @click="zoomOut" class="control-btn" title="缩小">➖</button>
      <button @click="centerMap" class="control-btn" title="回到中心">
        📍
      </button>
      <button
        @click="toggleSatellite"
        class="control-btn"
        :title="isSatellite ? '普通地图' : '卫星地图'"
      >
        {{ isSatellite ? '🗺️' : '🛰️' }}
      </button>
      <!-- 热力图开关 -->
      <button
        @click="toggleHeatmap"
        class="control-btn"
        :class="{ active: showHeatmap }"
        :title="showHeatmap ? '关闭热力图' : '打开热力图'"
      >
        🔥
      </button>
      <!-- 地铁线路开关 -->
      <button
        @click="toggleSubwayList()"
        class="control-btn"
        :class="{ active: showSubway }"
        :title="showSubway ? '隐藏地铁线路' : '显示地铁线路'"
      >
        🚋
      </button>
      <button @click="isShowSatellite" class="control-btn" title="显示卫星图">
        🚋
      </button>
      <button @click="isHideSatellite" class="control-btn" title="隐藏卫星图">
        🚋
      </button>
      <!-- 公交线路开关 -->
      <button
        @click="toggleBusList()"
        class="control-btn"
        :class="{ active: showBus }"
        :title="showBus ? '隐藏公交线路' : '显示公交线路'"
      >
        🚌
      </button>
      <!-- 区域名称开关 -->
      <button
        @click="toggleDistricts()"
        class="control-btn"
        :class="{ active: showDistricts }"
        :title="showDistricts ? '隐藏区域名称' : '显示区域名称'"
      >
        📍
      </button>
      <!-- 打开关闭标点 -->
      <button
        @click="markersShow"
        class="control-btn"
        :class="{ active: isShowMarkers }"
        :title="isShowMarkers ? '隐藏标记点' : '显示标记点'"
      >
        🛣️
      </button>

      <!-- 打开路线 -->
      <button
        @click="toggleRoute()"
        class="control-btn"
        :class="{ active: showToggle }"
        :title="showToggle ? '隐藏路线' : '显示路线'"
      >
        🚇
      </button>
      <button
        @click="toggleLundu()"
        class="control-btn"
        :class="{ active: showLundu }"
        :title="showLundu ? '隐藏轮渡' : '显示轮渡'"
      >
        🚢
      </button>
      <!-- 秩轨开关 -->
      <button
        @click="toggleZhigui()"
        class="control-btn"
        :class="{ active: showZhigui }"
        :title="showZhigui ? '隐藏秩轨' : '显示秩轨'"
      >
        🚅
      </button>
      <!-- 🚢 -->
      <button
        @click="searchAndDrawBinjiangBoundary()"
        class="control-btn"
        :class="{ active: BinjiangBoundary }"
        :title="BinjiangBoundary ? '隐藏滨江区' : '显示滨江区'"
      >
        🏙️
      </button>
    </div>

    <!-- 加载状态提示 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <span>地图加载中...</span>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-overlay">
      <span>❌ 地图加载失败，请检查API密钥</span>
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted, onUnmounted, watch, nextTick, version } from 'vue'
  import AMapLoader from '@amap/amap-jsapi-loader'
  window._AMapSecurityConfig = {
    securityJsCode: import.meta.env.VITE_AMAP_SECURITY_JS_CODE,
  }
  // Props
  const props = defineProps({
    center: {
      type: Array,
      // 杭州市
      default: () => [120.153576, 30.287459], // 杭州市中心坐标
    },
    zoom: {
      type: Number,
      default: 13,
    },
    showControls: {
      type: Boolean,
      default: false,
    },
    markers: {
      type: Array,
      default: () => [],
    },
  })

  // Emits
  const emit = defineEmits([
    'map-loaded',
    'marker-click',
    'map-click',
    'heatmap-toggle',
  ])

  // Refs
  const mapContainer = ref(null)
  const map = ref(null)
  const mapLoca = ref(null)
  const isSatellite = ref(false)
  const markerInstances = ref([])
  const heatmap = ref(null)
  const showHeatmap = ref(false)
  const loading = ref(true)
  const error = ref(false)
  const isShowMarkers = ref(false)
  const showToggle = ref(false)
  // 热力图配置
  const radius = ref(30)
  const opacity = ref(0.7)
  const busLines = ref([])
  const satelliteLayer = ref(null)
  const satellite = ref(null)
  const subwayLines = ref([]) // 存储所有地铁线路
  const subwayLinesObj = ref({}) // 存储所有地铁线路
  const lines = ['地铁1号线', '地铁4号线', '地铁5号线', '地铁6号线']

  // 在原有的 ref 定义中添加动画相关的 ref
  // 动画相关
  const showAnimation = ref(false)
  const animationMarker = ref(null)
  const animationPath = ref(null)
  const passedPath = ref(null)
  const isAnimating = ref(false)
  // 在原有的 ref 定义中添加
  const originalHeatmapOpacity = ref(0.7)
  const isAnimationComplete = ref(false)
  const isAnimationReturning = ref(false) // 标记动画是否在返程
  // 原始热力图数据
  const originalHeatmapData = ref(null)
  // 动画性能优化：节流相关
  const lastMovingCheckTime = ref(0)
  const movingCheckInterval = 100 // 每100ms检查一次，减少性能开销
  // 定时器管理器：统一管理所有setTimeout，防止内存泄漏
  const timerManager = {
    timers: new Set(), // 存储所有定时器ID
    /**
     * 创建定时器并自动管理
     * @param {Function} callback - 回调函数
     * @param {Number} delay - 延迟时间（毫秒）
     * @returns {Number} 定时器ID
     */
    setTimeout(callback, delay) {
      const timerId = setTimeout(() => {
        this.timers.delete(timerId) // 执行后自动清理
        callback()
      }, delay)
      this.timers.add(timerId)
      return timerId
    },
    /**
     * 清除指定定时器
     * @param {Number} timerId - 定时器ID
     */
    clearTimeout(timerId) {
      if (timerId && this.timers.has(timerId)) {
        clearTimeout(timerId)
        this.timers.delete(timerId)
      }
    },
    /**
     * 清除所有定时器
     */
    clearAll() {
      this.timers.forEach((timerId) => {
        clearTimeout(timerId)
      })
      this.timers.clear()
      console.log('已清除所有定时器')
    }
  }
  // 江南大道上的两个小车
  const carMarker1 = ref(null) // 小车1标记
  const carMarker2 = ref(null) // 小车2标记
  const car1Timer = ref(null) // 小车1定时器
  const car2Timer = ref(null) // 小车2定时器
  // 江南大道路径数据（从西向东）
  const jiangnanRoadPath1 = [
    [120.186000, 30.190000], // 江南大道西段起点
    [120.188000, 30.190500],
    [120.190000, 30.191000],
    [120.192000, 30.191500],
    [120.194000, 30.192000],
    [120.196000, 30.192500],
    [120.198000, 30.193000],
    [120.200000, 30.193500],
    [120.202000, 30.194000], // 江南大道东段终点
  ]
  // 江南大道反向路径（从东向西）
  const jiangnanRoadPath2 = [
    [120.202000, 30.194000], // 江南大道东段起点
    [120.200000, 30.193500],
    [120.198000, 30.193000],
    [120.196000, 30.192500],
    [120.194000, 30.192000],
    [120.192000, 30.191500],
    [120.190000, 30.191000],
    [120.188000, 30.190500],
    [120.186000, 30.190000], // 江南大道西段终点
  ]
  // 小车3（从南到北去往江南大道，然后返程）
  const carMarker3 = ref(null) // 小车3标记
  const car3Timer = ref(null) // 小车3定时器
  const car3IsReturning = ref(false) // 小车3是否在返程
  // 小车3去程路径（从南到北，到达江南大道）
  const car3PathToNorth = [
    [120.190000, 30.175000], // 起点（江南大道以南）
    [120.190000, 30.178000],
    [120.190000, 30.181000],
    [120.190000, 30.184000],
    [120.190000, 30.187000],
    [120.190000, 30.190000], // 到达江南大道
  ]
  // 小车3返程路径（从北到南，从江南大道返回）
  const car3PathToSouth = [
    [120.190000, 30.190000], // 起点（江南大道）
    [120.190000, 30.187000],
    [120.190000, 30.184000],
    [120.190000, 30.181000],
    [120.190000, 30.178000],
    [120.190000, 30.175000], // 返回到起点
  ]
  // 示例轨迹数据 - 到江南大道并返程
  const samplePath = [
    // 去程：从南方到江南大道
    [120.190000, 30.175000], // 起点（江南大道以南）
    [120.190000, 30.178000],
    [120.190000, 30.181000],
    [120.190000, 30.184000],
    [120.190000, 30.187000],
    [120.190000, 30.190000], // 到达江南大道
    // 返程：从江南大道返回起点
    [120.190000, 30.187000],
    [120.190000, 30.184000],
    [120.190000, 30.181000],
    [120.190000, 30.178000],
    [120.190000, 30.175000], // 返回到起点
  ]
  subwayLinesObj.value = lines.reduce((acc, line) => {
    acc[line] = []
    return acc
  }, {})
  const lineSearch = ref(null) // 线路搜索实例
  // 自定义的线
  const myLine = ref(null)
  const lundulineSpolyline = ref(null)
  const showLundu = ref(false)
  // 轮渡动画相关
  const lunduMarker = ref(null) // 轮渡标记
  const lunduTimer = ref(null) // 轮渡定时器
  const lunduIsReturning = ref(false) // 轮渡是否在返程
  // 轮渡的两个点（最后两个点）
  const lunduPoint1 = [120.169662, 30.196056]
  const lunduPoint2 = [120.16340400884269, 30.205130412808398]
  // 秩轨相关
  const showZhigui = ref(false) // 是否显示秩轨
  const zhiguiMarker = ref(null) // 秩轨标记
  const zhiguiTimer = ref(null) // 秩轨定时器
  const zhiguiPath = [
    [120.15916225391857, 30.182462235608693],
    [120.15919799031849, 30.179979321816333],
    [120.16444407394488, 30.18074496456386],
    [120.1677484245497, 30.1812455739622],
    [120.16659019829012, 30.1850736790491],
    [120.16226388319672, 30.183424667687618],
  ]
  const lunduLines = [
    [120.228456, 30.238765],
    [120.225678, 30.236543],
    [120.220123, 30.232109],
    [120.215876, 30.228765],
    [120.210123, 30.225109],
    [120.205123, 30.220109],
    [120.184516, 30.208264],
    [120.180153, 30.20486],
    [120.174532, 30.200524],
    [120.171712, 30.198751],
    [120.169662, 30.196056],
    [120.16340400884269,30.205130412808398]
  ]
  // 地铁线路相关
  const showSubway = ref(false)
  // 公交线路相关
  const showBus = ref(false)
  const busLinesObj = ref({
    '1507M': [],
    113: [],
  })
  // 显示区域名称和圆形透明块相关
  const showDistricts = ref(false)
  const districtMarkers = ref([]) // 存储区域名称标记
  const circleOverlay = ref(null) // 圆形透明块

  // 初始化地图
  const initMap = async () => {
    try {
      loading.value = true
      error.value = false
      console.log(
        'import.meta.env.VITE_AMAP_KEY',
        import.meta.env.VITE_AMAP_KEY
      )
      const AMap = await AMapLoader.load({
        key: import.meta.env.VITE_AMAP_KEY || '你的高德地图Key',
        version: '2.0',
        plugins: [
          'AMap.ToolBar',
          'AMap.Scale',
          'AMap.MapType',
          'AMap.HeatMap',
          'AMap.TileLayer',
          'AMap.LineSearch',
          'AMap.DistrictSearch',
          'AMap.Polygon',
          'AMap.MoveAnimation', // 新增动画插件
        ],
      })

      // 创建地图实例
      map.value = new AMap.Map(mapContainer.value, {
        viewMode: '2D',
        zoom: props.zoom,
        center: props.center,
        mapStyle: 'amap://styles/grey', // 确保地图样式正确
        zooms: [10, 18], // 限制缩放级别范围
        pitch: 0, // 禁用倾斜
        rotation: 0, // 禁用旋转
        animate: false, // 禁用动画
        doubleClickZoom: false, // 禁用双击缩放
        // 禁用滚轮缩放
        // scrollWheel: false,
        features: ['bg', 'point', 'road'], // 添加地图要素
      })

      satellite.value = new AMap.TileLayer.Satellite({
        map: null,
      })
      // 添加控件 - 确保地图有内容
      // map.value.addControl(new AMap.ToolBar({
      //   position: 'LT' // 左上角
      // }))
      // map.value.addControl(new AMap.Scale({
      //   position: 'LB' // 左下角
      // }))
      // 绑定事件
      map.value.on('click', (e) => {
        emit('map-click', e.lnglat)
      })

      // 地图加载完成事件
      map.value.on('complete', () => {
        console.log('地图加载完成！')
        loading.value = false
      })
      satelliteLayer.value = new window.AMap.TileLayer.Satellite()
      // 隐藏卫星
      satelliteLayer.value.hide()
      // 初始化地铁
      lineSearch.value = new AMap.LineSearch({
        pageIndex: 1,
        pageSize: 10,
        //杭州 滨江
        city: '杭州市',
        citylimit: false,

        extensions: 'all',
      })

      // 创建热力图实例的正确方式
      heatmap.value = new AMap.HeatMap(map.value, {
        radius: 100, // 热力图点半径
        opacity: [0, 0.8], // 热力图透明度范围
        gradient: {
          0.4: 'blue',
          0.6: 'cyan',
          0.7: 'lime',
          0.8: 'yellow',
          1.0: 'red',
        },
      })
      toggleDistricts()
      initAnimationElements(AMap)
      emit('map-loaded', map.value)
    } catch (error) {
      console.error('高德地图加载失败:', error)
      loading.value = false
      error.value = true
    }
  }
  // 初始化动画元素
  const initAnimationElements = (AMap) => {
    if (!AMap || !map.value) return

    // 创建轨迹线
    animationPath.value = new AMap.Polyline({
      map: map.value,
      path: samplePath,
      showDir: true,
      strokeColor: '#28F',
      strokeWeight: 6,
      visible: false,
    })

    // 创建已走过轨迹线
    passedPath.value = new AMap.Polyline({
      map: map.value,
      strokeColor: '#AF5',
      strokeWeight: 6,
      visible: false,
    })

    // 创建动画标记点
    animationMarker.value = new AMap.Marker({
      map: map.value,
      position: samplePath[0],
      icon: "https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png",
    offset: new AMap.Pixel(-10, -10), // 调整偏移量确保图片完全显示
      visible: false,
      // 禁用自动调整地图
      autoRotation: false,
    })
    //* 先隐藏 ‘
    animationPath.value.hide()

    // 初始化江南大道上的两个小车
    initJiangnanRoadCars(AMap)

    // 监听移动事件（优化：添加节流以减少性能开销）
    animationMarker.value.on('moving', (e) => {
      // 更新已走过的路径（这个操作比较轻量，可以频繁执行）
      passedPath.value.setPath(e.passedPath)
      
      // 节流检查：每100ms才执行一次距离计算等耗时操作
      const now = Date.now()
      if (now - lastMovingCheckTime.value < movingCheckInterval) {
        return // 跳过本次检查
      }
      lastMovingCheckTime.value = now
      
      // 地图中心跟随移动
      // map.value.setCenter(e.target.getPosition(), true)
      
      // 检查是否到达终点（减少路径获取次数，使用缓存）
      const currentPath = animationPath.value.getPath()
      const currentPosition = e.target.getPosition()
      const lastPoint = currentPath[currentPath.length - 1]
      
      // 只在去程时检查是否到达江南大道
      if (!isAnimationReturning.value) {
        const jiangnanPoint = currentPath[5] // 江南大道的位置
        const distanceToJiangnan = AMap.GeometryUtil.distance(currentPosition, jiangnanPoint)
        
        // 如果到达江南大道，标记开始返程
        if (distanceToJiangnan < 50) {
          isAnimationReturning.value = true
          console.log('到达江南大道，开始返程')
        }
      }

      // 只在返程时检查是否到达终点
      if (isAnimationReturning.value && !isAnimationComplete.value) {
        // 计算与终点的距离
        const distance = AMap.GeometryUtil.distance(currentPosition, lastPoint)

        // 如果距离小于50米，认为到达终点（返程完成）
        if (distance < 50) {
          isAnimationComplete.value = true
          onAnimationComplete()
        }
      }
    })
    // 添加移动结束事件监听
    animationMarker.value.on('moveend', () => {
      const currentPath = animationPath.value.getPath()
      const currentPosition = animationMarker.value.getPosition()
      const lastPoint = currentPath[currentPath.length - 1]
      const distance = AMap.GeometryUtil.distance(currentPosition, lastPoint)
      
      // 只有在返程完成时才降低热力值
      if (distance < 50 && !isAnimationComplete.value && isAnimationReturning.value) {
        isAnimationComplete.value = true
        onAnimationComplete()
      }
    })
  }
  // 到达终点时的回调函数（返程完成时）
  const onAnimationComplete = () => {
    console.log('onAnimationComplete被调用', {
      hasHeatmap: !!heatmap.value,
      showHeatmap: showHeatmap.value,
      hasAnimationPath: !!animationPath.value,
      isReturning: isAnimationReturning.value,
      hasOriginalData: !!originalHeatmapData.value
    })
    
    // 降低热力图热力值（只降低返程路径的热力值）
    if (heatmap.value && showHeatmap.value && animationPath.value && isAnimationReturning.value) {
      // 确保原始数据已初始化
      if (!originalHeatmapData.value) {
        console.warn('原始热力图数据未初始化，无法降低热力值')
        return
      }
      
      const fullPath = animationPath.value.getPath()
      // 只取返程路径（从索引6开始，即从江南大道返回的部分）
      const returnPath = fullPath.slice(6) // 返程路径：从江南大道返回起点
      console.log('返程路径:', returnPath)
      reduceHeatmapValueByPath(returnPath, 0.5) // 降低50%的热力值
      console.log('返程完成，热力图热力值已降低')
    } else {
      console.log('降低热力值的条件不满足')
    }
  }
  // 动画控制方法
  const toggleAnimation = () => {
    showAnimation.value = !showAnimation.value
    if (showAnimation.value) {
      // 检查热力图是否已初始化
      if (!originalHeatmapData.value) {
        console.warn('热力图数据未初始化，请先打开热力图')
      }
      if (!showHeatmap.value) {
        console.warn('热力图未显示，降低热力值功能需要先打开热力图')
      }
      showAnimationElements()
    } else {
      hideAnimationElements()
      stopAnimation()
    }
  }

  const showAnimationElements = () => {
    if (animationPath.value) animationPath.value.show()
    if (passedPath.value) passedPath.value.show()
    if (animationMarker.value) animationMarker.value.show()
    startAnimation()
    // 调整地图视图以适应轨迹
    // if (animationPath.value) {
    //   map.value.setFitView([animationPath.value])
    // }
  }

  const hideAnimationElements = () => {
    if (animationPath.value) animationPath.value.hide()
    if (passedPath.value) passedPath.value.hide()
    if (animationMarker.value) animationMarker.value.hide()
  }

  const startAnimation = () => {
    if (!animationMarker.value || !animationPath.value) return

    isAnimating.value = true
    isAnimationComplete.value = false // 重置完成状态
    isAnimationReturning.value = false // 重置返程状态
    lastMovingCheckTime.value = 0 // 重置节流时间戳
    
    // 注意：不在启动时恢复原始热力值，保持之前的降低效果
    // 如果需要重置热力值，可以在toggleHeatmap中重新设置
    console.log('启动动画，返程完成后将降低热力值')
    
    animationMarker.value.moveAlong(animationPath.value.getPath(), {
      duration: 200, // 每段时长，可根据实际调整
      autoRotation: true, // 自动旋转方向
    })
  }

  const pauseAnimation = () => {
    if (animationMarker.value && isAnimating.value) {
      animationMarker.value.pauseMove()
    }
  }

  const resumeAnimation = () => {
    if (animationMarker.value && isAnimating.value) {
      animationMarker.value.resumeMove()
    }
  }

  const stopAnimation = () => {
    if (animationMarker.value) {
      animationMarker.value.stopMove()
      isAnimating.value = false
      isAnimationComplete.value = false // 重置完成状态
      resetAnimation()
      // 停止时也恢复热力图透明度
      // if (heatmap.value && showHeatmap.value) {
      //   heatmap.value.setOptions({ opacity: [0, originalHeatmapOpacity.value] })
      // }
    }
  }

  const resetAnimation = () => {
    if (animationMarker.value && animationPath.value) {
      // 重置标记点到起点
      animationMarker.value.setPosition(samplePath[0])
      // 清除已走过轨迹
      passedPath.value.setPath([])
      isAnimationComplete.value = false // 重置完成状态
      isAnimationReturning.value = false // 重置返程状态
      // 重置时恢复热力图透明度
      // if (heatmap.value && showHeatmap.value) {
      //   heatmap.value.setOptions({ opacity: [0, originalHeatmapOpacity.value] })
      // }
    }
  }

  // 设置自定义轨迹路径
  const setAnimationPath = (path) => {
    if (animationPath.value) {
      animationPath.value.setPath(path)
      resetAnimation()

      // 更新地图视图
      // map.value.setFitView([animationPath.value])
    }
  }

  /**
   * 初始化江南大道上的两个小车
   * 实现小车在地图上不断出现/消失的循环动画
   * @param {Object} AMap - 高德地图API对象
   */
  const initJiangnanRoadCars = (AMap) => {
    if (!AMap || !map.value) return

    // 创建小车1标记（从西向东）
    carMarker1.value = new AMap.Marker({
      map: map.value,
      position: jiangnanRoadPath1[0],
      icon: "https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png",
      offset: new AMap.Pixel(-10, -10),
      visible: false,
      autoRotation: true,
      zIndex: 100,
    })

    // 创建小车2标记（从东向西）
    carMarker2.value = new AMap.Marker({
      map: map.value,
      position: jiangnanRoadPath2[0],
      icon: "https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png",
      offset: new AMap.Pixel(-10, -10),
      visible: false,
      autoRotation: true,
      zIndex: 100,
    })

    // 创建小车3标记（从南到北去往江南大道，然后返程）
    carMarker3.value = new AMap.Marker({
      map: map.value,
      position: car3PathToNorth[0],
      icon: "https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png",
      offset: new AMap.Pixel(-10, -10),
      visible: false,
      autoRotation: true,
      zIndex: 100,
    })

    // 监听小车1移动完成事件
    carMarker1.value.on('moveend', () => {
      // 清除之前的定时器（如果存在）
      if (car1Timer.value) {
        timerManager.clearTimeout(car1Timer.value)
      }
      // 移动完成后隐藏小车
      carMarker1.value.hide()
      // 延迟2-4秒后重新出现并开始移动
      const delay = Math.random() * 2000 + 2000 // 2-4秒随机延迟
      car1Timer.value = timerManager.setTimeout(() => {
        startCar1Animation()
      }, delay)
    })

    // 监听小车2移动完成事件
    carMarker2.value.on('moveend', () => {
      // 清除之前的定时器（如果存在）
      if (car2Timer.value) {
        timerManager.clearTimeout(car2Timer.value)
      }
      // 移动完成后隐藏小车
      carMarker2.value.hide()
      // 延迟2-4秒后重新出现并开始移动
      const delay = Math.random() * 2000 + 2000 // 2-4秒随机延迟
      car2Timer.value = timerManager.setTimeout(() => {
        startCar2Animation()
      }, delay)
    })

    // 监听小车3移动完成事件（实现去程和返程切换）
    carMarker3.value.on('moveend', () => {
      // 清除之前的定时器（如果存在）
      if (car3Timer.value) {
        timerManager.clearTimeout(car3Timer.value)
      }
      // 移动完成后隐藏小车
      carMarker3.value.hide()
      // 切换返程状态（为下次启动做准备）
      car3IsReturning.value = !car3IsReturning.value
      // 延迟2-4秒后重新出现并开始移动
      const delay = Math.random() * 2000 + 2000 // 2-4秒随机延迟
      car3Timer.value = timerManager.setTimeout(() => {
        startCar3Animation()
      }, delay)
    })

    // 延迟启动小车动画，让小车错开时间出现
    timerManager.setTimeout(() => {
      startCar1Animation()
    }, 1000)

    timerManager.setTimeout(() => {
      startCar2Animation()
    }, 3000)

    timerManager.setTimeout(() => {
      startCar3Animation()
    }, 5000)
  }

  /**
   * 计算两点之间的角度（用于设置图标初始方向）
   * @param {Array} point1 - 起点 [lng, lat]
   * @param {Array} point2 - 终点 [lng, lat]
   * @returns {Number} 角度（度）
   */
  const calculateAngle = (point1, point2) => {
    const [lng1, lat1] = point1
    const [lng2, lat2] = point2
    const dx = lng2 - lng1
    const dy = lat2 - lat1
    // 计算角度（弧度转度）
    const angle = (Math.atan2(dy, dx) * 180) / Math.PI
    return angle
  }

  /**
   * 启动小车1的动画（从西向东）
   */
  const startCar1Animation = () => {
    if (!carMarker1.value) return

    // 重置小车位置到起点
    carMarker1.value.setPosition(jiangnanRoadPath1[0])
    // 显示小车
    carMarker1.value.show()
    // 开始移动动画
    carMarker1.value.moveAlong(jiangnanRoadPath1, {
      duration: 150, // 每段移动时长
      autoRotation: true, // 自动旋转方向
    })
  }

  /**
   * 启动小车2的动画（从东向西）
   */
  const startCar2Animation = () => {
    if (!carMarker2.value) return

    // 重置小车位置到起点
    carMarker2.value.setPosition(jiangnanRoadPath2[0])
    // 显示小车
    carMarker2.value.show()
    // 开始移动动画
    carMarker2.value.moveAlong(jiangnanRoadPath2, {
      duration: 150, // 每段移动时长
      autoRotation: true, // 自动旋转方向
    })
  }

  /**
   * 启动小车3的动画（从南到北去往江南大道，然后返程）
   * 根据car3IsReturning状态决定是去程还是返程
   */
  const startCar3Animation = () => {
    if (!carMarker3.value) return

    if (car3IsReturning.value) {
      // 返程：从江南大道返回南方
      carMarker3.value.setPosition(car3PathToSouth[0])
      carMarker3.value.show()
      carMarker3.value.moveAlong(car3PathToSouth, {
        duration: 150, // 每段移动时长
        autoRotation: true, // 自动旋转方向
      })
    } else {
      // 去程：从南方去往江南大道
      carMarker3.value.setPosition(car3PathToNorth[0])
      carMarker3.value.show()
      carMarker3.value.moveAlong(car3PathToNorth, {
        duration: 150, // 每段移动时长
        autoRotation: true, // 自动旋转方向
      })
    }
  }

  /**
   * 停止所有小车动画
   */
  const stopJiangnanRoadCars = () => {
    if (car1Timer.value) {
      timerManager.clearTimeout(car1Timer.value)
      car1Timer.value = null
    }
    if (car2Timer.value) {
      timerManager.clearTimeout(car2Timer.value)
      car2Timer.value = null
    }
    if (car3Timer.value) {
      timerManager.clearTimeout(car3Timer.value)
      car3Timer.value = null
    }
    if (carMarker1.value) {
      carMarker1.value.stopMove()
      carMarker1.value.hide()
    }
    if (carMarker2.value) {
      carMarker2.value.stopMove()
      carMarker2.value.hide()
    }
    if (carMarker3.value) {
      carMarker3.value.stopMove()
      carMarker3.value.hide()
    }
  }

  const initLundu = () => {
    const AMap = window.AMap
    if (!AMap) return null

    const polyline = new AMap.Polyline({
      map: map.value,
      path: lunduLines,
      strokeColor: '#0CDDE4', // 根据线路名称获取颜色
      strokeOpacity: 0.8,
      strokeWeight: 8,
      //虚线
      strokeStyle: 'dashed',
      strokeDasharray: [10, 5], // 虚线
    })

    // 存储线路信息
    polyline.lineName = '轮渡线路'

    return polyline
  }
  const BinjiangBoundary = ref(false)
  const binjiangqupolygon = ref(null)
  // 搜索并绘制滨江区的行政规划图
  const searchAndDrawBinjiangBoundary = () => {
    BinjiangBoundary.value = !BinjiangBoundary.value
    const AMap = window.AMap
    if (!AMap || !map.value) return
    // 使用DistrictSearch查询区级边界
    const districtSearch = new AMap.DistrictSearch({
      level: 'district',
      subdistrict: 0, // 不返回下级行政区
      city: '杭州',
      extensions: 'all', // 返回边界坐标
    })
    if (!BinjiangBoundary.value) {
      map.value.remove(binjiangqupolygon.value)
      binjiangqupolygon.value.hide
      return
    }
    // 搜索“杭州市滨江区”
    districtSearch.search('滨江区', function (status, result) {
      if (status === 'complete') {
        var district = result.districtList[0]
        if (district && district.boundaries) {
          // 滨江区的边界可能由多个多边形组成，我们通常取第一个主边界
          var boundary = district.boundaries[0]

          // 创建多边形覆盖物
          console.log('boundary', boundary)
          // 解决  Uncaught Invalid Object: Pixel(NaN, NaN)
          boundary = boundary.map((item) => {
            return [item.lng, item.lat]
          })
          console.log('boundary', boundary)
          binjiangqupolygon.value = new AMap.Polygon({
            path: boundary,
            strokeColor: '#B3EBAF', // 线颜色
            strokeWeight: 2, // 线宽
            fillColor: '#B3EBAF', // 填充色
            fillOpacity: 0.35, // 填充透明度
          })
          // 将多边形添加到地图上
          map.value.add(binjiangqupolygon.value)
          binjiangqupolygon.value.show()
        } else {
          console.log('未找到滨江区边界数据')
        }
      } else {
        console.log('行政区查询失败：' + status)
      }
    })
  }
  /**
   * 初始化轮渡动画标记
   */
  const initLunduAnimation = () => {
    const AMap = window.AMap
    if (!AMap || !map.value) return

    // 创建轮渡标记（使用🚢图标，旋转90度）
    lunduMarker.value = new AMap.Marker({
      map: map.value,
      position: lunduPoint1, // 从第一个点开始
      content: '<div style="font-size: 28px; text-align: center; line-height: 1; transform: rotate(90deg); display: inline-block;">🚢</div>',
      offset: new AMap.Pixel(-14, -14),
      visible: false,
      autoRotation: true,
      zIndex: 100,
    })

    // 监听移动完成事件，实现往返
    lunduMarker.value.on('moveend', () => {
      // 清除之前的定时器（如果存在）
      if (lunduTimer.value) {
        timerManager.clearTimeout(lunduTimer.value)
      }
      // 移动完成后，切换方向
      lunduIsReturning.value = !lunduIsReturning.value
      // 延迟2秒后继续移动
      lunduTimer.value = timerManager.setTimeout(() => {
        startLunduAnimation()
      }, 2000)
    })
  }

  /**
   * 启动轮渡动画
   */
  const startLunduAnimation = () => {
    if (!lunduMarker.value) return

    if (lunduIsReturning.value) {
      // 返程：从点2返回点1
      lunduMarker.value.setPosition(lunduPoint2)
      lunduMarker.value.show()
      lunduMarker.value.moveAlong([lunduPoint2, lunduPoint1], {
        duration: 200, // 每段移动时长
        autoRotation: true, // 自动旋转方向
      })
    } else {
      // 去程：从点1到点2
      lunduMarker.value.setPosition(lunduPoint1)
      lunduMarker.value.show()
      lunduMarker.value.moveAlong([lunduPoint1, lunduPoint2], {
        duration: 200, // 每段移动时长
        autoRotation: true, // 自动旋转方向
      })
    }
  }

  /**
   * 停止并清除轮渡动画
   */
  const stopLunduAnimation = () => {
    if (lunduTimer.value) {
      timerManager.clearTimeout(lunduTimer.value)
      lunduTimer.value = null
    }
    if (lunduMarker.value) {
      lunduMarker.value.stopMove()
      lunduMarker.value.hide()
    }
    lunduIsReturning.value = false
  }

  const toggleLundu = () => {
    showLundu.value = !showLundu.value
    if (showLundu.value) {
      // 显示轮渡线路
      lundulineSpolyline.value = initLundu()
      lundulineSpolyline.value.show()
      
      // 初始化并启动轮渡动画
      if (!lunduMarker.value) {
        initLunduAnimation()
      }
      // 延迟启动动画，让轮渡错开时间出现
      timerManager.setTimeout(() => {
        startLunduAnimation()
      }, 1000)
    } else {
      // 隐藏轮渡线路
      map.value.remove(lundulineSpolyline.value)
      
      // 停止并清除轮渡动画
      stopLunduAnimation()
    }
  }

  /**
   * 初始化秩轨动画标记
   */
  const initZhiguiAnimation = () => {
    const AMap = window.AMap
    if (!AMap || !map.value) return

    // 创建秩轨标记（使用🚅图标，确保能与轨迹平行）
    zhiguiMarker.value = new AMap.Marker({
      map: map.value,
      position: zhiguiPath[0], // 从第一个点开始
      content: '<div style="font-size: 28px; text-align: center; line-height: 1; width: 28px; height: 28px; display: flex; align-items: center; justify-content: center;">🚌</div>',
      offset: new AMap.Pixel(-14, -14), // 图标中心偏移
      visible: false,
      autoRotation: true, // 自动旋转，使图标与轨迹平行
      zIndex: 100,
    })

    // 监听移动完成事件，实现循环
    zhiguiMarker.value.on('moveend', () => {
      // 移动完成后，重新从起点开始循环
      // 清除之前的定时器（如果存在）
      if (zhiguiTimer.value) {
        timerManager.clearTimeout(zhiguiTimer.value)
      }
      // 延迟2秒后继续移动
      zhiguiTimer.value = timerManager.setTimeout(() => {
        startZhiguiAnimation()
      }, 2000)
    })
  }

  /**
   * 启动秩轨动画
   */
  const startZhiguiAnimation = () => {
    if (!zhiguiMarker.value || zhiguiPath.length < 2) return

    // 重置到起点
    zhiguiMarker.value.setPosition(zhiguiPath[0])
    // 计算初始角度，使图标与轨迹方向平行
    const initialAngle = calculateAngle(zhiguiPath[0], zhiguiPath[1])
    zhiguiMarker.value.setAngle(initialAngle)
    // 显示标记
    zhiguiMarker.value.show()
    // 沿着路径移动
    zhiguiMarker.value.moveAlong(zhiguiPath, {
      duration: 200, // 每段移动时长
      autoRotation: true, // 自动旋转方向，使图标与轨迹平行
    })
  }

  /**
   * 停止并清除秩轨动画
   */
  const stopZhiguiAnimation = () => {
    if (zhiguiTimer.value) {
      timerManager.clearTimeout(zhiguiTimer.value)
      zhiguiTimer.value = null
    }
    if (zhiguiMarker.value) {
      zhiguiMarker.value.stopMove()
      zhiguiMarker.value.hide()
    }
  }

  /**
   * 切换秩轨显示/隐藏
   */
  const toggleZhigui = () => {
    showZhigui.value = !showZhigui.value
    if (showZhigui.value) {
      // 初始化并启动秩轨动画
      if (!zhiguiMarker.value) {
        initZhiguiAnimation()
      }
      // 延迟启动动画
      timerManager.setTimeout(() => {
        startZhiguiAnimation()
      }, 1000)
    } else {
      // 停止并清除秩轨动画
      stopZhiguiAnimation()
    }
  }

  // init 地铁
  const initSubway = async (name = null) => {
    console.log('initSubway1', name)
    if (!lineSearch.value || !map.value) return

    try {
      // 搜索杭州地铁1号线:cite[5]
      lineSearch.value.search(name, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          console.log(`地铁${name}查询成功:`, result)

          // 绘制所有找到的线路
          if (result.lineInfo && result.lineInfo.length > 0) {
            result.lineInfo.forEach((lineInfo, index) => {
              if (lineInfo.path && lineInfo.path.length > 0) {
                let path = extractBinjiangSection(
                  lineInfo.path,
                  binjiangBoundary.value
                )
                console.log('path', path)
                if (path && path.length > 0) {
                  const polyline = drawSubwayLine(path, name)
                  subwayLinesObj.value[name].push(polyline)
                  // 默认隐藏地铁线路
                  polyline.show()
                }
              }
            })

            console.log(
              `成功加载 ${subwayLinesObj.value[name].length} 条地铁线路`
            )
          }
        } else {
          console.error('地铁查询失败:', status, result)
        }
      })
    } catch (error) {
      console.error('初始化地铁线路失败:', error)
    }
  }
  const drawMyLine = (path, lineName) => {
    const AMap = window.AMap
    if (!AMap) return null

    const polyline = new AMap.Polyline({
      map: map.value,
      path: path,
      strokeColor: '#E67818', // 根据线路名称获取颜色
      strokeOpacity: 0.8,
      strokeWeight: 8,
      strokeStyle: 'solid',
      strokeDasharray: [0, 0], // 实线
    })

    // 存储线路信息
    polyline.lineName = lineName

    return polyline
  }
  // 绘制地铁线路:cite[5]:cite[6]
  const drawSubwayLine = (path, lineName) => {
    const AMap = window.AMap
    if (!AMap) return null

    const polyline = new AMap.Polyline({
      map: map.value,
      path: path,
      strokeColor: getLineColor(lineName), // 根据线路名称获取颜色
      strokeOpacity: 0.8,
      strokeWeight: 8,
      strokeStyle: 'solid',
      strokeDasharray: [0, 0], // 实线
    })

    // 存储线路信息
    polyline.lineName = lineName

    return polyline
  }

  // 根据线路名称获取颜色
  const getLineColor = (lineName) => {
    console.log('lineName', lineName)
    const colorMap = {
      地铁1号线: '#E12311',
      地铁2号线: '#BF8157',
      地铁3号线: '#037AC1',
      地铁4号线: '#83C21F',
      地铁5号线: '#E67818',
      地铁6号线: '#291771',
      地铁7号线: '#9267A6',
      地铁8号线: '#808080',
      地铁9号线: '#FFD700',
      地铁10号线: '#00CED1',
      地铁16号线: '#FF4500',
      地铁19号线: '#fff',
    }

    return colorMap[lineName] || '#3366FF' // 默认蓝色
  }
  const clearLine = () => {
    map.value.remove(myLine.value)
  }
  const toggleRoute = (
    ls = [
      [120.190826, 30.194148],
      [120.186623, 30.16643],
      [120.1685231311056, 30.161578213867102],
    ]
  ) => {
    showToggle.value = !showToggle.value
    if (showToggle.value) {
      myLine.value = drawMyLine(ls, '地铁1号线')
      console.log('myLine.value', myLine.value)
      myLine.value.show()
    } else {
      clearLine()
    }
  }
  // 清除所有地铁线路
  const clearSubwayLines = () => {
    // if (map.value && subwayLines.value.length > 0) {
    //   subwayLines.value.forEach((polyline) => {
    //     map.value.remove(polyline);
    //   });
    //   subwayLines.value = [];
    // }
    if (map.value && subwayLinesObj.value) {
      Object.keys(subwayLinesObj.value).forEach((key) => {
        subwayLinesObj.value[key].forEach((polyline) => {
          map.value.remove(polyline)
        })
        subwayLinesObj.value[key] = []
      })
    }
  }

  // 显示/隐藏地铁线路
  const toggleSubwayList = async (names = lines) => {
    showSubway.value = !showSubway.value
    console.log('names', names)
    await getBinjiangBoundary()
    // ['地铁1号线', '地铁4号线', '地铁5号线', '地铁6号线']
    names.forEach((name) => {
      toggleSubway(name)
    })
  }
  const toggleSubway = (name = '一号线') => {
    if (showSubway.value) {
      if (subwayLinesObj.value[name].length === 0) {
        // 清除之前的地铁线路
        clearSubwayLines()
        // 如果还没有加载地铁线路，先初始化
        initSubway(name).then(() => {
          // 加载完成后显示
          subwayLinesObj.value[name].forEach((polyline) => {
            polyline.show()
          })
        })
      } else {
        // 直接显示已有线路
        subwayLinesObj.value[name].forEach((polyline) => {
          polyline.show()
        })
      }
    } else {
      // 隐藏地铁线路
      subwayLinesObj.value[name].forEach((polyline) => {
        polyline.hide()
      })
    }
  }

  // 在toggleSubway方法后面添加公交线路相关方法

  // init 公交
  const initBus = async (name = null) => {
    console.log('initBus', name)
    if (!lineSearch.value || !map.value) return

    try {
      // 搜索公交线路
      lineSearch.value.search(name, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          console.log(`公交${name}查询成功:`, result)

          // 绘制所有找到的线路
          if (result.lineInfo && result.lineInfo.length > 0) {
            result.lineInfo.forEach((lineInfo, index) => {
              if (lineInfo.path && lineInfo.path.length > 0) {
                // 使用extractBinjiangSection过滤出滨江区域内的线路
                let path = extractBinjiangSection(
                  lineInfo.path,
                  binjiangBoundary.value
                )
                console.log('bus path', path)
                if (path && path.length > 0) {
                  const polyline = drawBusLine(path, name)
                  busLinesObj.value[name].push(polyline)
                  // 默认显示公交线路
                  polyline.show()
                }
              }
            })

            console.log(`成功加载 ${busLinesObj.value[name].length} 条公交线路`)
          }
        } else {
          console.error('公交查询失败:', status, result)
        }
      })
    } catch (error) {
      console.error('初始化公交线路失败:', error)
    }
  }

  // 绘制公交线路
  const drawBusLine = (path, lineName) => {
    const AMap = window.AMap
    if (!AMap) return null

    const polyline = new AMap.Polyline({
      map: map.value,
      path: path,
      strokeColor: getBusLineColor(lineName), // 根据线路名称获取颜色
      strokeOpacity: 0.8,
      strokeWeight: 8,
      strokeStyle: 'solid',
      strokeDasharray: [0, 0], // 实线
    })

    // 存储线路信息
    polyline.lineName = lineName

    return polyline
  }

  // 根据公交线路名称获取颜色
  const getBusLineColor = (lineName) => {
    const colorMap = {
      '1507M': '#0CB5BC', // 红色
      113: '#FF4500', // 蓝色
    }

    return colorMap[lineName] || '#FFA500' // 默认橙色
  }

  // 清除所有公交线路
  const clearBusLines = () => {
    if (map.value && busLinesObj.value) {
      Object.keys(busLinesObj.value).forEach((key) => {
        busLinesObj.value[key].forEach((polyline) => {
          map.value.remove(polyline)
        })
        busLinesObj.value[key] = []
      })
    }
  }

  // 显示/隐藏公交线路
  const toggleBusList = async (names = ['1507M', '113']) => {
    showBus.value = !showBus.value
    await getBinjiangBoundary()
    names.forEach((name) => {
      toggleBus(name)
    })
  }

  const toggleBus = (name) => {
    if (showBus.value) {
      if (busLinesObj.value[name].length === 0) {
        // 清除之前的公交线路
        clearBusLines()
        // 如果还没有加载公交线路，先初始化
        initBus(name).then(() => {
          // 加载完成后显示
          busLinesObj.value[name].forEach((polyline) => {
            polyline.show()
          })
        })
      } else {
        // 直接显示已有线路
        busLinesObj.value[name].forEach((polyline) => {
          polyline.show()
        })
      }
    } else {
      // 隐藏公交线路
      busLinesObj.value[name].forEach((polyline) => {
        polyline.hide()
      })
    }
  }

  //判断浏览区是否支持canvas
  function isSupportCanvas() {
    var elem = document.createElement('canvas')
    return !!(elem.getContext && elem.getContext('2d'))
  }
  // 切换热力图显示

  // 切换热力图显示
  const toggleHeatmap = () => {
    showHeatmap.value = !showHeatmap.value
    if (!heatmap.value) return
    const heatDataEffect = {
      max: 20,
      data: [
        // 滨江区江南大道沿线热力图数据点
        { lng: 120.16040765201387, lat: 30.182556856527608, count: 10 },
        { lng: 120.16415763779139, lat: 30.183612252825966, count: 15 },
        { lng: 120.16415763779139, lat: 30.183612252825966, count: 4 },
        { lng: 120.16764599719215, lat: 30.18670299117388, count: 5 },
        { lng: 120.17331458011597, lat: 30.189115207263637, count: 10 },
        { lng: 120.17898316303945, lat: 30.191979637687897, count: 10 },
        { lng: 120.186000, lat: 30.190000, count: 10 }, // 江南大道西段
        { lng: 120.188000, lat: 30.190500, count: 8 },  // 江南大道西段偏中
        { lng: 120.192000, lat: 30.191500, count: 4 },  // 江南大道中段偏东
        { lng: 120.194000, lat: 30.192000, count: 20 }, // 江南大道中段东
        { lng: 120.198000, lat: 30.193000, count: 10 }, // 江南大道东段
        { lng: 120.202000, lat: 30.194000, count: 10 }, // 江南大道东段,
        // 滨江区其他位置也零散放一些
        /**
         * 120.18930206005814,30.15405942002026
         * 120.20366485217937,30.14646633967248
         * 120.22341991764188,30.157747544466055
         * 120.24068344754448,30.179424607657076
         * 120.25383661288515,30.177647978758493
         * 120.22054266527289,30.21104324423172
         * 120.1878275138605,30.172042597179484
         */
        { lng: 120.18930206005814, lat: 30.15405942002026, count: 10 },
        { lng: 120.20366485217937, lat: 30.14646633967248, count: 15 },
        { lng: 120.22054266527289, lat: 30.21104324423172, count: 10 },
        { lng: 120.1878275138605, lat: 30.172042597179484, count: 10 },
      ],
    }
    // 保存原始热力图数据（深拷贝）
    if (!originalHeatmapData.value) {
      originalHeatmapData.value = JSON.parse(JSON.stringify(heatDataEffect))
    }
    console.log('showHeatmap', showHeatmap.value)
    if (heatmap.value) {
      if (showHeatmap.value) {
        heatmap.value.setDataSet(heatDataEffect)
        console.log('heatmap.value', heatmap.value)
        heatmap.value.setOptions({ opacity: [0, originalHeatmapOpacity.value] })
        heatmap.value.show()
      } else {
        heatmap.value.hide()
      }
    }
  }

  /**
   * 将所有热力点的值降低为5
   * @param {Array} path - 小车经过的路径坐标数组（参数保留以保持接口兼容）
   * @param {Number} reduceRatio - 降低比例（参数保留以保持接口兼容）
   */
  const reduceHeatmapValueByPath = (path, reduceRatio = 0.5) => {
    console.log('reduceHeatmapValueByPath被调用，将所有热力点降低为5', {
      hasHeatmap: !!heatmap.value,
      showHeatmap: showHeatmap.value,
      hasOriginalData: !!originalHeatmapData.value
    })
    
    if (!heatmap.value || !showHeatmap.value || !originalHeatmapData.value) {
      console.warn('降低热力值的条件不满足')
      return
    }

    // 深拷贝原始数据
    const newHeatData = JSON.parse(JSON.stringify(originalHeatmapData.value))
    let reducedCount = 0 // 统计被降低的点数

    // 直接将所有热力点的值设置为5
    newHeatData.data = newHeatData.data.map((heatPoint) => {
      if (heatPoint.count > 5) {
        reducedCount++
      }
      return { ...heatPoint, count: 5 }
    })

    console.log(`将所有${newHeatData.data.length}个热力点的值都降低为5，其中${reducedCount}个点的值被降低了`)
    
    // 更新热力图数据
    heatmap.value.setDataSet(newHeatData)
    console.log('热力图数据已更新')
  }

  const markersShow = () => {
    isShowMarkers.value = !isShowMarkers.value
    if (isShowMarkers.value) {
      // 确保在显示标记点时能正确获取AMap对象
      addMarkers(window.AMap)
    } else {
      clearMarkers()
    }
  }
  // 添加标记点
  const addMarkers = (AMap) => {
    // 确保AMap对象可用
    const AMapInstance = AMap || window.AMap
    if (!AMapInstance || !map.value || !props.markers.length) return

    clearMarkers()

    props.markers.forEach((markerData) => {
      const marker = new AMapInstance.Marker({
        position: markerData.position,
        title: markerData.title,
        content: createMarkerContent(markerData),
        offset: new AMapInstance.Pixel(-13, -30),
      })

      marker.on('click', () => {
        console.log('markerData', markerData)
        sendMessageToCSharp({
          type: 'marker',
          id: markerData.id,
          name: markerData.title,
          position: markerData.position,
        })
      })

      map.value.add(marker)
      markerInstances.value.push(marker)
    })
  }

  // 创建标记点内容
  const createMarkerContent = (markerData) => {
    // 如果标记点数据包含useIconImage属性，则使用IconImage组件
    if (markerData.useIconImage) {
      return `<div class="icon-image-marker" style="width:81px;height:97px;position:relative;display:flex;justify-content:center">
     <img src="${markerData.bgIconImage}" alt="${markerData.title}" style="width: 100%; height: 100%; position: absolute; top: 0; left: 0; z-index: 1;">
      <img src="${markerData.iconImage}" alt="${markerData.title}" style="width: 40px;height:40px;margin-top:23px; position: relative; z-index: 2;">
    </div>`
    }

    // 默认标记点样式
    return `<div style="
    background: #ff4444;
    color: white;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
    white-space: nowrap;
  ">${markerData.title}</div>`
  }

  // 清除所有标记
  const clearMarkers = () => {
    if (map.value && markerInstances.value.length) {
      map.value.remove(markerInstances.value)
      markerInstances.value = []
    }
  }

  // 地图控制方法
  const zoomIn = () => map.value?.zoomIn()
  const zoomOut = () => map.value?.zoomOut()

  const centerMap = () => {
    if (map.value) {
      map.value.setCenter(props.center)
      map.value.setZoom(props.zoom)
    }
  }

  const toggleSatellite = (bool) => {
    if (map.value) {
      isSatellite.value = bool
      if (isSatellite.value) {
        satellite.value.setMap(map.value)
      } else {
        satellite.value.setMap(null)
      }
    }
  }
  // 显示卫星图
  const isShowSatellite = () => {
    if (!map.value) return
    isSatellite.value = true
    if (isSatellite.value) {
      satellite.value.setMap(map.value)
    }
  }
  // 隐藏卫星图
  const isHideSatellite = () => {
    if (!map.value) return
    isSatellite.value = false
    if (!isSatellite.value) {
      satellite.value.setMap(null)
    }
  }
  // 滨江
  const districtSearch = ref(null)
  const binjiangBoundary = ref(null)
  function getBinjiangBoundary() {
    return new Promise((resolve, reject) => {
      // 使用DistrictSearch查询区级边界
      districtSearch.value = new AMap.DistrictSearch({
        level: 'district',
        subdistrict: 0, // 不返回下级行政区
        extensions: 'all', // 返回边界坐标
      })
      // 搜索“杭州市滨江区”
      districtSearch.value.search('滨江区', function (status, result) {
        if (status === 'complete') {
          var district = result.districtList[0]
          if (district && district.boundaries) {
            // 滨江区的边界可能由多个多边形组成，我们通常取第一个主边界
            binjiangBoundary.value = district.boundaries[0]
            resolve(binjiangBoundary.value)
          } else {
            reject('未找到滨江区边界数据')
          }
        } else {
          reject('行政区查询失败：' + status)
        }
      })
    })
  }
  // 高德地图JS API v2.0 提供了 AMap.GeometryUtil 方法
  function isPointInPolygon(point, polygon) {
    return AMap.GeometryUtil.isPointInRing(point, polygon)
  }
  // 步骤4：从完整路径中提取位于滨江区内的线段
  function extractBinjiangSection(fullPath, boundary) {
    var sections = [] // 存储所有在区内的线段，可能有多段
    var currentSection = [] // 当前正在构建的线段

    for (var i = 0; i < fullPath.length; i++) {
      var point = new AMap.LngLat(fullPath[i].lng, fullPath[i].lat)

      if (isPointInPolygon(point, boundary)) {
        // 如果当前点在滨江区内，将其加入当前线段
        currentSection.push(point)
      } else {
        // 如果当前点不在滨江区内
        if (currentSection.length > 0) {
          // 并且当前线段不为空，说明一个连续段结束
          sections.push(currentSection)
          currentSection = [] // 重置当前线段
        }
        // 如果当前线段为空，则什么都不做，继续下一个点
      }
    }

    // 循环结束后，检查最后一段
    if (currentSection.length > 0) {
      sections.push(currentSection)
    }

    return sections
  }

  // 显示杭州市所有区的名字
  const showDistrictNames = async () => {
    const AMap = window.AMap
    if (!AMap || !map.value) return

    // 清除现有的区域标记
    clearDistrictMarkers()

    // 杭州市区县列表及对应的中心位置和圆块大小
    const districts = [
      { name: '上城区', position: [120.16, 30.25], radius: 800 },
      { name: '下城区', position: [120.15, 30.28], radius: 700 },
      { name: '江干区', position: [120.2, 30.27], radius: 1000 },
      { name: '拱墅区', position: [120.13, 30.3], radius: 900 },
      { name: '西湖区', position: [120.08, 30.25], radius: 1200 },
      { name: '滨江区', position: [120.2, 30.2], radius: 1900 },
      { name: '萧山区', position: [120.27, 30.17], radius: 1500 },
      { name: '余杭区', position: [120.3, 30.25], radius: 1800 },
      { name: '临安区', position: [120.3, 30.35], radius: 2000 },
      { name: '富阳区', position: [120.25, 30.05], radius: 1000 },
      { name: '桐庐县', position: [120.0, 30.0], radius: 2200 },
      { name: '淳安县', position: [119.5, 29.7], radius: 2500 },
      { name: '建德市', position: [120.0, 30.4], radius: 1900 },
    ]

    // 为每个区县添加标记和圆块
    districts.forEach((district) => {
      // 添加区域名称标记
      const marker = new AMap.Marker({
        position: district.position,
        title: district.name,
        content: `<div style="
        color: #fff;
        padding: 8px 12px;
        font-size: 14px;
        font-weight: bold;
        white-space: nowrap;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
        border-radius: 16px;
      ">${district.name}</div>`,
        offset: new AMap.Pixel(-30, -15),
        // 设置为可点击
        clickable: true,
      })

      // 为滨江区marker添加点击事件
      if (district.name === '滨江区') {
        marker.on('click', function (e) {
          // 使公交线路/地铁线路/轮渡线路显示/隐藏
          toggleBusList()
          toggleSubwayList()
          toggleLundu()
          // 点击滨江后remove掉其他点
          clearDistrictMarkers()
          searchAndDrawBinjiangBoundary()
        })
      }

      map.value.add(marker)
      districtMarkers.value.push(marker)

      // 为每个区创建黄色透明圆块
      const circle = new AMap.Circle({
        center: district.position,
        radius: district.radius,
        fillColor: 'rgba(255, 255, 0, 0.2)', // 黄色半透明填充
        fillOpacity: 0.2,
        strokeColor: 'rgba(255, 255, 0, 0.4)', // 黄色边框
        strokeOpacity: 0.4,
        strokeWeight: 1,
      })

      map.value.add(circle)
      districtMarkers.value.push(circle) // 将圆块也添加到标记数组中，便于统一清除
    })
  }

  // 创建大的圆形透明块

  // 清除区域标记
  const clearDistrictMarkers = (name) => {
    if (map.value && districtMarkers.value.length > 0) {
      districtMarkers.value.forEach((marker) => {
        map.value.remove(marker)
      })
      districtMarkers.value = []
    }

    // 清除圆形覆盖物
    clearCircleOverlay()
  }
  // 清除原型覆盖物 圆形覆盖物
  const clearCircleOverlay = () => {
    if (circleOverlay.value) {
      map.value.remove(circleOverlay.value)
      circleOverlay.value = null
    }
  }

  // 切换区域显示
  const toggleDistricts = () => {
    showDistricts.value = !showDistricts.value
    if (showDistricts.value) {
      showDistrictNames()
    } else {
      clearDistrictMarkers()
    }
  }
  // 给c#发送消息
  const sendMessageToCSharp = (data) => {
    if (window.vuplex) {
      sendMessage(data)
    } else {
      window.addEventListener('vuplexready', sendMessage)
    }
  }
  function sendMessage({ type, ...data }) {
    window.vuplex.postMessage({
      type,
      ...data,
    })
  }
  // 添加区域标记显示/隐藏方法
  const toggleDistrictMarkers = () => {
    if (districtMarkers.value.length > 0) {
      // 如果已有标记，切换显示/隐藏
      districtMarkers.value.forEach((marker) => {
        if (marker.getVisible && marker.getVisible()) {
          marker.hide && marker.hide()
        } else {
          marker.show && marker.show()
        }
      })
    } else {
      // 如果没有标记，显示区域名称
      showDistrictNames()
    }
    // 更新显示状态
    showDistricts.value = !showDistricts.value
  }

  // 生命周期
  onMounted(() => {
    nextTick(() => {
      initMap()
    })
  })

  onUnmounted(() => {
    // 停止并清理江南大道上的小车
    stopJiangnanRoadCars()
    // 停止并清理轮渡动画
    stopLunduAnimation()
    // 停止并清理秩轨动画
    stopZhiguiAnimation()
    
    if (map.value) {
      // 清理动画相关元素
      if (animationMarker.value) {
        map.value.remove(animationMarker.value)
      }
      if (animationPath.value) {
        map.value.remove(animationPath.value)
      }
      if (passedPath.value) {
        map.value.remove(passedPath.value)
      }
      // 清理小车相关元素
      if (carMarker1.value) {
        map.value.remove(carMarker1.value)
      }
      if (carMarker2.value) {
        map.value.remove(carMarker2.value)
      }
      if (carMarker3.value) {
        map.value.remove(carMarker3.value)
      }
      // 清理轮渡标记
      if (lunduMarker.value) {
        map.value.remove(lunduMarker.value)
      }
      // 清理秩轨标记
      if (zhiguiMarker.value) {
        map.value.remove(zhiguiMarker.value)
      }
      map.value.destroy()
    }
    // 清理所有定时器
    timerManager.clearAll()
  })
  window.addEventListener('zoomIn', zoomIn)
  console.log('放大：zoomIn')
  console.log('缩小：zoomOut')
  console.log('居中：centerMap')
  console.log('热力图：toggleHeatmap')
  console.log('显示卫星图：isShowSatellite')
  console.log('隐藏卫星图：isHideSatellite')
  console.log('地铁：toggleSubwayList') // 地铁
  console.log('公交：toggleBusList') // 公交
  console.log('轮渡：toggleLundu')
  console.log('秩轨：toggleZhigui')
  console.log('标记点：markersShow')
  console.log('路线：toggleRoute')
  console.log('区域名称：toggleDistricts')
  console.log('滨江区域图：searchAndDrawBinjiangBoundary')

  window.addEventListener('zoomOut', zoomOut)
  window.addEventListener('centerMap', centerMap)

  window.addEventListener('isShowSatellite', isShowSatellite)
  window.addEventListener('isHideSatellite', isHideSatellite)

  window.addEventListener('toggleHeatmap', toggleHeatmap)
  // 地铁
  window.addEventListener('toggleSubwayList', toggleSubwayList)
  // 公交
  window.addEventListener('toggleBusList', toggleBusList)
  //轮渡
  window.addEventListener('toggleLundu', toggleLundu)
  // 秩轨
  window.addEventListener('toggleZhigui', toggleZhigui)
  // 标记点
  window.addEventListener('markersShow', markersShow)
  // 路线
  window.addEventListener('toggleRoute', toggleRoute)
  // 区域名称
  window.addEventListener('toggleDistricts', toggleDistricts)
  // 显示小车动画
  window.addEventListener('toggleAnimation', toggleAnimation)
  // 滨江区域图
  window.addEventListener(
    'searchAndDrawBinjiangBoundary',
    searchAndDrawBinjiangBoundary
  )
</script>

<style scoped>
  ::v-deep(.amap-logo),
  ::v-deep(.amap-copyright),
  ::v-deep(.amap-maptypecontrol) {
    opacity: 0;
  }
  .amap-container {
    position: relative;
    width: 100%;
    height: 100%;
    min-height: 500px;
    border: 1px solid #e0e0e0;
    box-sizing: border-box;
    border-radius: 8px;
    overflow: hidden;
  }

  .map {
    width: 100%;
    height: 100%;
    min-height: 500px;
  }

  .map-controls {
    position: absolute;
    top: 20px;
    left: 20px;
    z-index: 1000;
    display: flex;
    flex-direction: column;
    gap: 8px;
    background: rgba(255, 255, 255, 0.95);
    padding: 12px;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
    border: 1px solid #e0e0e0;
  }

  .control-btn {
    width: 44px;
    height: 44px;
    background: white;
    border: 2px solid #e0e0e0;
    border-radius: 8px;
    cursor: pointer;
    font-size: 18px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
  }

  .control-btn:hover {
    background: #f8f9fa;
    border-color: #007bff;
    transform: translateY(-2px);
  }

  .control-btn.active {
    background: #007bff;
    color: white;
    border-color: #0056b3;
    box-shadow: 0 2px 8px rgba(0, 123, 255, 0.3);
  }

  .heatmap-controls {
    position: absolute;
    top: 20px;
    left: 20px;
    z-index: 1000;
    background: rgba(255, 255, 255, 0.95);
    padding: 16px;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
    border: 1px solid #e0e0e0;
    min-width: 220px;
  }

  .heatmap-controls h4 {
    margin: 0 0 12px 0;
    color: #333;
    font-size: 14px;
    font-weight: 600;
  }

  .control-group {
    margin-bottom: 16px;
  }

  .control-group:last-child {
    margin-bottom: 0;
  }

  .control-group label {
    display: block;
    margin-bottom: 6px;
    font-size: 12px;
    color: #666;
    font-weight: 500;
  }

  .slider {
    width: 100%;
    height: 6px;
    border-radius: 3px;
    background: #ddd;
    outline: none;
    appearance: none;
    -webkit-appearance: none;
    transition: background 0.2s;
  }

  .slider:hover {
    background: #ccc;
  }

  .slider::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 18px;
    height: 18px;
    border-radius: 50%;
    background: #007bff;
    cursor: pointer;
    border: 2px solid white;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  }

  .slider::-moz-range-thumb {
    width: 18px;
    height: 18px;
    border-radius: 50%;
    background: #007bff;
    cursor: pointer;
    border: 2px solid white;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  }

  .loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.9);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    z-index: 2000;
  }

  .loading-spinner {
    width: 40px;
    height: 40px;
    border: 4px solid #f3f3f3;
    border-top: 4px solid #007bff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 12px;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }

  .error-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.9);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 2000;
    color: #dc3545;
    font-weight: 500;
  }
  /* 新增动画控制面板样式 */
  .animation-controls {
    display: flex;
    flex-direction: column;
    gap: 6px;
    margin-top: 8px;
    padding-top: 8px;
    border-top: 1px solid #e0e0e0;
  }

  .anim-btn {
    width: 40px;
    height: 36px;
    background: white;
    border: 1px solid #e0e0e0;
    border-radius: 6px;
    cursor: pointer;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
  }

  .anim-btn:hover {
    background: #f8f9fa;
    border-color: #007bff;
    transform: translateY(-1px);
  }

  /* 响应式调整 */
  @media (max-width: 768px) {
    .animation-controls {
      flex-direction: row;
      flex-wrap: wrap;
    }

    .anim-btn {
      width: 36px;
      height: 36px;
    }
  }
  ::v-deep .amap-icon {
    overflow: unset !important;
  }
</style>
